package org.nimi317.web_gis.interceptor;

import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.nimi317.web_gis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @author thunderobot
 */
@Component
public class DemoInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        List<Cookie> list = Arrays.stream(cookies).filter(cookie -> "sign".equals(cookie.getName())).toList();
        String referer = request.getHeader("Referer");
        if (ObjectUtil.isNotEmpty(list) && ObjectUtil.isNotNull(referer) && referer.contains("localhost:5173/demo")) {
            Set<Object> set = redisService.getCacheSet("sign");
            String value = list.get(0).getValue();
            boolean contains = set.contains(value);
            if (contains) {
                set.remove(value);
                redisService.setCacheSet("sign", set);
            }
            return contains;
        } else {
            return false;
        }
    }
}
